<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文案创作测试页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 40px;
        }

        .form-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 30px;
        }

        .form-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 15px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-secondary {
            background: #6c757d;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn-success {
            background: #28a745;
        }

        .btn-success:hover {
            background: #218838;
        }

        .output-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 30px;
            margin-top: 30px;
        }

        .output-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .output-container {
            background: #2d3748;
            border-radius: 8px;
            padding: 20px;
            color: #e2e8f0;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.6;
            max-height: 500px;
            overflow-y: auto;
            position: relative;
        }

        .output-container::-webkit-scrollbar {
            width: 8px;
        }

        .output-container::-webkit-scrollbar-track {
            background: #4a5568;
            border-radius: 4px;
        }

        .output-container::-webkit-scrollbar-thumb {
            background: #718096;
            border-radius: 4px;
        }

        .output-container::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }

        .status {
            padding: 10px 15px;
            border-radius: 6px;
            margin-bottom: 15px;
            font-weight: 600;
        }

        .status.connecting {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }

        .status.connected {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status.completed {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .log-entry {
            margin-bottom: 8px;
            padding: 5px 0;
            border-bottom: 1px solid #4a5568;
        }

        .log-entry:last-child {
            border-bottom: none;
        }

        .timestamp {
            color: #a0aec0;
            font-size: 12px;
        }

        .content-text {
            color: #e2e8f0;
            word-wrap: break-word;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .controls {
            margin-top: 20px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .info-box {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .info-box h3 {
            color: #1976d2;
            margin-bottom: 10px;
            font-size: 1.1em;
        }

        .info-box p {
            color: #424242;
            line-height: 1.5;
        }

        .session-info {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .session-info h3 {
            color: #856404;
            margin-bottom: 10px;
            font-size: 1.1em;
        }

        .session-info p {
            color: #856404;
            line-height: 1.5;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .content {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>文案创作测试页面</h1>
            <p>测试文案创作功能的SSE流式输出</p>
        </div>

        <div class="content">
            <div class="info-box">
                <h3>使用说明</h3>
                <p>首先填写服务端地址和token信息，然后获取SSE会话ID，填写创作参数后点击"开始创作"按钮，系统将通过SSE方式实时返回文案创作结果。</p>
            </div>

            <div class="session-info" id="sessionInfo" style="display: none;">
                <h3>会话信息</h3>
                <p>会话ID: <span id="sessionIdDisplay"></span></p>
                <p>状态: <span id="sessionStatus">未连接</span></p>
            </div>

            <div class="form-section">
                <h2>创作参数设置</h2>
                
                <div class="form-group">
                    <label for="baseUrl">服务端地址</label>
                    <input type="text" id="baseUrl" value="http://localhost:8080" placeholder="请输入服务端地址">
                </div>

                <div class="form-group">
                    <label for="token">Token</label>
                    <input type="text" id="token" placeholder="请输入token信息" style="font-family: monospace;">
                </div>

                <div class="form-group">
                    <label for="message">创作内容</label>
                    <textarea id="message" placeholder="请输入要创作的内容，例如：请帮我创作一篇关于科技发展的文案"></textarea>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="weekTaskId">周任务ID (可选)</label>
                        <input type="number" id="weekTaskId" placeholder="周任务ID">
                    </div>
                    <div class="form-group">
                        <label for="hotTopicId">热榜话题ID (可选)</label>
                        <input type="number" id="hotTopicId" placeholder="热榜话题ID">
                    </div>
                    <div class="form-group">
                        <label for="douyinId">热榜话题ID (可选)</label>
                        <input type="number" id="douyinId" placeholder="抖音ID">
                    </div>
                </div>



                <div class="form-row">
                    <div class="form-group">
                        <label for="recommendTag">推荐标签 (可选)</label>
                        <input type="text" id="recommendTag" placeholder="推荐标签">
                    </div>
                    <div class="form-group">
                        <label for="desc">描述 (可选)</label>
                        <input type="text" id="desc" placeholder="创作描述或关键词">
                    </div>
                </div>

                <div class="controls">
                    <button class="btn btn-success" onclick="getSessionId()" id="getSessionBtn">
                        <span class="loading" id="sessionLoadingSpinner" style="display: none;"></span>
                        获取会话ID
                    </button>
                    <button class="btn" onclick="startContentCreate()" id="startBtn" disabled>
                        <span class="loading" id="loadingSpinner" style="display: none;"></span>
                        开始创作
                    </button>
                    <button class="btn btn-secondary" onclick="clearOutput()">清空输出</button>
                </div>
            </div>

            <div class="output-section">
                <h2>创作结果输出</h2>
                <div id="status" class="status" style="display: none;"></div>
                <div id="output" class="output-container">
                    <div class="log-entry">
                        <span class="timestamp">[等待开始...]</span>
                        <span class="content-text">请先填写服务端地址和token信息，然后获取会话ID，填写创作内容并点击"开始创作"按钮</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentSessionId = null;
        let isConnecting = false;

        // 获取会话ID
        async function getSessionId() {
            const baseUrl = document.getElementById('baseUrl').value.trim();
            const token = document.getElementById('token').value.trim();
            
            if (!baseUrl) {
                log('错误: 请输入服务端地址');
                return;
            }
            
            if (!token) {
                log('错误: 请输入token信息');
                return;
            }

            const getSessionBtn = document.getElementById('getSessionBtn');
            const sessionLoadingSpinner = document.getElementById('sessionLoadingSpinner');
            
            getSessionBtn.disabled = true;
            sessionLoadingSpinner.style.display = 'inline-block';
            getSessionBtn.innerHTML = '<span class="loading" id="sessionLoadingSpinner"></span>获取中...';

            log('开始获取SSE会话ID...');

            try {
                const response = await fetch(`${baseUrl}/api/client/sse/connect`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
                }

                const result = await response.json();
                
                if (result.code === 200 && result.data && result.data.sessionId) {
                    currentSessionId = result.data.sessionId;
                    document.getElementById('sessionIdDisplay').textContent = currentSessionId;
                    document.getElementById('sessionStatus').textContent = '已获取';
                    document.getElementById('sessionInfo').style.display = 'block';
                    document.getElementById('startBtn').disabled = false;
                    
                    log(`成功获取会话ID: ${currentSessionId}`);
                    updateStatus('会话ID获取成功', 'connected');
                } else {
                    throw new Error('获取会话ID失败: ' + (result.message || '未知错误'));
                }

            } catch (error) {
                log(`获取会话ID失败: ${error.message}`);
                updateStatus('获取会话ID失败', 'error');
            } finally {
                getSessionBtn.disabled = false;
                sessionLoadingSpinner.style.display = 'none';
                getSessionBtn.innerHTML = '获取会话ID';
            }
        }

        // 日志输出
        function log(message) {
            const output = document.getElementById('output');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> <span class="content-text">${message}</span>`;
            output.appendChild(logEntry);
            output.scrollTop = output.scrollHeight;
        }

        // 清空输出
        function clearOutput() {
            const output = document.getElementById('output');
            output.innerHTML = '<div class="log-entry"><span class="timestamp">[已清空]</span> <span class="content-text">输出已清空</span></div>';
        }

        // 更新状态
        function updateStatus(message, type) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = `status ${type}`;
            status.style.display = 'block';
        }

        // 开始文案创作
        async function startContentCreate() {
            if (!currentSessionId) {
                log('错误: 请先获取会话ID');
                return;
            }

            if (isConnecting) {
                log('正在连接中，请稍候...');
                return;
            }

            const baseUrl = document.getElementById('baseUrl').value.trim();
            const token = document.getElementById('token').value.trim();
            const message = document.getElementById('message').value.trim();
            const weekTaskId = document.getElementById('weekTaskId').value;
            const hotTopicId = document.getElementById('hotTopicId').value;
            const douyinId = document.getElementById('douyinId').value;
            const recommendTag = document.getElementById('recommendTag').value.trim();
            const desc = document.getElementById('desc').value.trim();

            if (!baseUrl) {
                log('错误: 请输入服务端地址');
                return;
            }
            
            if (!token) {
                log('错误: 请输入token信息');
                return;
            }

            if (!message) {
                log('错误: 请输入创作内容');
                return;
            }

            isConnecting = true;
            const startBtn = document.getElementById('startBtn');
            const loadingSpinner = document.getElementById('loadingSpinner');
            
            startBtn.disabled = true;
            loadingSpinner.style.display = 'inline-block';
            startBtn.innerHTML = '<span class="loading" id="loadingSpinner"></span>创作中...';

            clearOutput();
            updateStatus('正在连接服务器...', 'connecting');
            log('开始文案创作请求...');
            log(`使用会话ID: ${currentSessionId}`);

            try {
                // 构建请求参数
                const requestBody = {
                    message: message,
                    sessionId: currentSessionId
                };

                if (weekTaskId) {
                    requestBody.weekTaskId = parseInt(weekTaskId);
                }
                if (hotTopicId) {
                    requestBody.hotTopicId = parseInt(hotTopicId);
                }
                if (douyinId) {
                    requestBody.douyinId = parseInt(douyinId);
                }
                if (recommendTag) {
                    requestBody.recommendTag = recommendTag;
                }
                if (desc) {
                    requestBody.desc = desc;
                }

                log('请求参数: ' + JSON.stringify(requestBody, null, 2));

                // 发送POST请求
                const response = await fetch(`${baseUrl}/api/client/index/contentCreate`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token,
                        'X-Session-ID': currentSessionId
                    },
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
                }

                updateStatus('连接成功，开始接收流式数据...', 'connected');
                log('连接成功，开始接收流式数据...');

                // 读取流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let lineCount = 0;
                let totalBytes = 0;
                let chunkCount = 0;

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) {
                        log('流式输出完成');
                        updateStatus('创作完成', 'completed');
                        break;
                    }

                    chunkCount++;
                    const newChunk = decoder.decode(value, { stream: true });
                    buffer += newChunk;
                    totalBytes += value.length;

                    log(`接收到第${chunkCount}个数据块: ${newChunk.length} 字符，总计: ${totalBytes} 字节`);

                    // 处理完整行
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';

                    for (const line of lines) {
                        if (line.trim()) {
                            lineCount++;
                            log(`处理第${lineCount}行: ${line.substring(0, 100)}${line.length > 100 ? '...' : ''}`);
                            
                            // 解析SSE数据
                            if (line.startsWith('data: ')) {
                                try {
                                    const jsonData = line.substring(6);
                                    const jsonObj = JSON.parse(jsonData);
                                    
                                    if (jsonObj.event === 'delta' && jsonObj.data && jsonObj.data.content) {
                                        log(`提取到内容: ${jsonObj.data.content}`);
                                    } else if (jsonObj.event === 'complete') {
                                        log(`创作完成: ${jsonObj.message || '文案创作已完成'}`);
                                        updateStatus('创作完成', 'completed');
                                    } else if (jsonObj.event === 'error') {
                                        log(`错误: ${jsonObj.message}`);
                                        updateStatus('创作失败', 'error');
                                    } else {
                                        log(`事件: ${jsonObj.event || 'unknown'}`);
                                    }
                                } catch (e) {
                                    log(`解析JSON失败: ${e.message}`);
                                }
                            } else {
                                log(`原始数据: ${line}`);
                            }
                        }
                    }

                    // 处理缓冲区剩余内容
                    if (buffer && !buffer.includes('\n')) {
                        log(`缓冲区内容: ${buffer}`);
                    }
                }

            } catch (error) {
                log(`连接失败: ${error.message}`);
                updateStatus('连接失败', 'error');
            } finally {
                isConnecting = false;
                startBtn.disabled = false;
                loadingSpinner.style.display = 'none';
                startBtn.innerHTML = '开始创作';
            }
        }

        // 页面加载时的初始化
        window.onload = function() {
            log('页面加载完成，请先填写服务端地址和token信息，然后获取会话ID');
        };
    </script>
</body>
</html> 